//
//  Utils.swift
//  ptbuy
//
//  Created by MyMac on 2024/11/19.
//

import Foundation
import SwiftUI
import UIKit
import SwiftUI

class Utils{
    
    // 将字符串数组转换为 JSON 字符串
    public static  func convertArrayToJsonString(stringArray:[String]) ->String{
        let encoder = JSONEncoder()
        encoder.outputFormatting = .prettyPrinted
           
        do {
            let data = try encoder.encode(stringArray)
            if let jsonString = String(data: data, encoding: .utf8) {
                return jsonString
            }
        } catch {
            print("Error encoding array to JSON: \(error)")
            return ""
        }
        return "";
    }
       
    // 将 JSON 字符串转换为字符串数组
    public static func convertJsonStringToArray(jsonString:String)->[String] {
        let decoder = JSONDecoder()
           
        guard let data = jsonString.data(using: .utf8) else {
            print("Invalid JSON string")
            return []
        }
           
        do {
            let decodedArray = try decoder.decode([String].self, from: data)
            return  decodedArray
        } catch {
            print("Error decoding JSON to array: \(error)")
            return []
        }
    }


    public static   func getDocumentsDirectory() -> URL {
        // 获取应用的 Documents 目录路径
        let paths = FileManager.default.urls(
            for: .documentDirectory,
            in: .userDomainMask
        )
        return paths[0]
    }
    
    //保存后的访问
    public static  func loadImage(fileName:String) -> UIImage? {
        let filename = getDocumentsDirectory().appendingPathComponent(fileName)
        if let imageData = try? Data(contentsOf: filename) {
            return UIImage(data: imageData)
        }
        return nil
    }
    
    public static func saveImage(image: UIImage,fileName:String) {
        // 保存图像到文件系统
        if let data = image.jpegData(compressionQuality: 1.0) {
            let filename = Utils.getDocumentsDirectory().appendingPathComponent(
                fileName
            )
            do {
                try data.write(to: filename)
                print("图片保存成功: \(filename)")
            } catch {
                print("保存图片失败: \(error)")
            }
        }
    }
    
    // 获取应用版本号
    public static  func appVersion() -> String {
        guard let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String else {
            return "Unknown"
        }
        return version
    }

       
    // 获取应用构建号
    public static  func appBuild() -> String {
        guard let build = Bundle.main.infoDictionary?["CFBundleVersion"] as? String else {
            return "Unknown"
        }
        return build
    }
}
